﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using QFlow.Data;
using QFlow.Core;
using System.Xml.Linq;
using QFlow.Windows.Forms;
using QFlow.Windows;

namespace QFlow
{
    /// <summary>
    /// Main Form class that contains the Main methods
    /// </summary>
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        internal static void Main()
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            QFlow.Data.QFlowDbContext context = new QFlow.Data.QFlowDbContext();

            if (!context.DatabaseExists())
            {
                Splach splachfrm = new Splach(context);
                splachfrm.ShowDialog();
            }

            //Accounting Data
            if (context.AccountingLogs.Count() > 0)
            {
                var log = context.AccountingLogs.GetLatestLog();
                Accounting.PurchaseCredit = log.PurchaseCredit;
                Accounting.PurchaseReturn = log.PurchaseReturn;

                Accounting.SalesCredit = log.SalesCredit;
                Accounting.SalesReturn = log.SalesReturn;
            }

            //initilzations
            LoggingManager.Context = context;
            PurchaseOrderManager.Context = context;
            SaleOrderManager.Context = context;
            AccountingManager.Context = context;

            Login loginfrm = new Login(context, false);
            if (loginfrm.ShowDialog() == DialogResult.OK)
            {
                Application.Run(new MainForm(context));
            }
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            XDocument doc = XDocument.Load("Exceptions.xml");
            Exception ex = e.ExceptionObject as Exception;

            XElement elm = new XElement("Exception");
            XAttribute time = new XAttribute("Time", DateTime.Now.ToString("dd-MM-yyyy"));
            XAttribute msg = null;
            if (ex != null)
            {

                msg = new XAttribute("MSG", ex.Message);


            }
            else
            {
                msg = new XAttribute("MSG", e.ExceptionObject);
            }

            elm.Add(time, msg);
            doc.Root.Add(elm);
            doc.Save("Exceptions.xml");
        }
    }
}

